package com.example.plantuml.model;

import lombok.Data;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * 请求跟踪信息模型
 */
@Data
public class RequestTrace {
    private String traceId;           // 跟踪ID
    private String requestUrl;        // 请求URL
    private String httpMethod;        // HTTP方法
    private String clientIp;          // 客户端IP
    private long startTime;           // 请求开始时间
    private long endTime;             // 请求结束时间
    private long totalDuration;       // 总耗时
    private MethodCall rootMethod;    // 根方法调用(Controller方法)

    public RequestTrace(HttpServletRequest request) {
        this.traceId = UUID.randomUUID().toString().substring(0, 10);
        this.requestUrl = request.getRequestURI();
        this.httpMethod = request.getMethod();
        this.clientIp = getClientIp(request);
        this.startTime = System.currentTimeMillis();
    }

    public void calculateTotalDuration() {
        this.totalDuration = endTime - startTime;
    }

    // 获取客户端真实IP
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
